package com.chaodev.base.controller;

import com.github.pagehelper.PageInfo;
import com.chaodev.base.model.*;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.RoleDTO;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.service.IRoleService;
import com.chaodev.base.utils.JwtUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/role")
public class RoleController {
    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @Autowired
    private IRoleService roleService;

    @Value("${myserver.name}")
    private String myserverName;

    @Value("${platform}")
    private String platform;


    /**
     * @Description: 查询数据列表
     * @Author: xy
     * @CreateDate: 2019/12/26 15:19
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 15:19
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/getRoleList")
    @ApiOperation(value = "获取角色列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result roleQuery(@RequestBody @ApiParam(value = "分页传入参数") DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_PAGE", dataPage.getPage());
            map.put("P_PAGESIZE", dataPage.getRows());
            map.put("P_KEYWORD", dataPage.getKeyword());
            map.put("P_SORTNAME", dataPage.getSort());
            map.put("P_SORTORDER", dataPage.getOrder());
            map.put("P_USERID", userInfo.getUserId());
            map.put("U_ROLE_ID", userInfo.getRoleId());
            PageInfo<RoleDTO> pageInfo = roleService.roleQuery(map);
            result.setCode(0);
            Map<String, Object> reMap = new HashMap<>();
            reMap.put("total", pageInfo.getTotal());
            reMap.put("rows", pageInfo.getList());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(reMap);

            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dataPage.toString(), "获取角色列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dataPage.toString(), "获取角色列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 角色添加
     * @Author: xy
     * @CreateDate: 2019/12/26 15:21
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 15:21
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/save")
    @ResponseBody
    @ApiOperation(value = "新增/编辑角色")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result roleAdd(@RequestBody @ApiParam(value = "角色信息") Role role, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            boolean flag = false;
            //判断新增还是修改
            if (null != role.getRoleId() && !"".equals(role.getRoleId())){
                //修改操作
                flag = roleService.roleUpd(role);
            }else{
                //新增操作
                role.setCreateUser(userInfo.getUserId());
                //插入角色信息并返回主键至对象role中
                if("mysql".equals(platform)){
                    flag = roleService.roleAddMysql(role);
                }
                if("oracle".equals(platform)){
                    flag = roleService.roleAddOracle(role);
                }
                if(flag){
                    //更新parentRoleIds,mysql才去更新
                    if("mysql".equals(platform)){
                        //获取父级角色信息
                        Role pRole = roleService.getRoleByRoleId(role.getParentRoleId());
                        Role updRole = new Role();
                        updRole.setRoleId(role.getRoleId());
                        updRole.setParentRoleIds(pRole.getParentRoleIds().concat(",").concat(role.getRoleId()));
                        roleService.roleUpd(updRole);
                    }
                }
            }
            if (flag) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("提交成功");
            } else {
                result.setCode(-1);
                result.setMsg("提交失败");
            }
            logService.logAdd(role.toString(), "新增/编辑角色", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(role.toString(), "新增/编辑角色", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 角色删除
     * @Author: xy
     * @CreateDate: 2019/12/26 16:24
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 16:24
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/delete")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "删除角色")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result roleDelete(@RequestBody @ApiParam(value = "角色信息") Role role, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            boolean flag = roleService.roleDelete(role);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("删除成功");
            } else {
                result.setCode(-1);
                result.setMsg("删除失败");
            }
            logService.logAdd(role.toString(), "删除角色", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(role.toString(), "删除角色", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取权限数据
     * @Author: xy
     * @CreateDate: 2019/12/26 17:41
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 17:41
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/getRoleMenuCode")
    @ResponseBody
    @ApiOperation(value = "获取权限数据")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getPowerData(@RequestBody @ApiParam(value = "权限信息") Power power, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("V_ROLE_ID", power.getRoleId());
            List<Power> list = roleService.getPowerData(map);
            result.setCode(0);
            result.setData(list);
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(power.toString(), "获取权限数据", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(power.toString(), "获取权限数据", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/grantRoleMenuCode")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "权限新增")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result PowerAdd(@RequestBody @ApiParam(value = "权限新增") Power power, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            power.setCreateUser(userInfo.getUserId());
            power.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            boolean flag = roleService.powerAdd(power);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("授权成功");
            } else {
                result.setCode(-1);
                result.setMsg("授权失败");
            }
            logService.logAdd(power.toString(), "权限新增", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(power.toString(), "权限新增", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @RequestMapping(value = "/getRoleOptions", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取角色上级树")
    @SuppressWarnings("all")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getRoleOptions(@RequestBody @ApiParam(value = "节点信息") Tree tree, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_TYPE", "");
            map.put("P_ROLE_ID", "");
            //用户自身的角色id
            map.put("U_ROLE_ID", userInfo.getRoleId());
            List<Map<String, Object>> list = roleService.getRoleTree(map);
            Iterator<Map<String, Object>> it = list.iterator();
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            while (it.hasNext()) {
                Map<String, Object> resultMap = it.next();
                Map<String, Object> dataMap = new HashMap<>();
                if (resultMap.get("pid").toString().equals("0")) {
                    dataMap.put("value", resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString());
                    dataMap.put("label", resultMap.get("TEXT_NAME") == null ? "" : resultMap.get("TEXT_NAME").toString());
                    dataMap.put("dsc", resultMap.get("ROLE_DSC") == null ? "" : resultMap.get("ROLE_DSC").toString());
                    String nodeid = resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString();
                    List<Map<String, Object>> listChild = new ArrayList<>();
                    if (resultMap.get("STATE").equals("closed")) {
                        listChild = getChildMap(nodeid, list);
                    }
                    dataMap.put("children", listChild);
                    resultList.add(dataMap);
                }
            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(resultList);

            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(tree.toString(), "获取菜单上级树", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(tree.toString(), "获取菜单上级树", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    public List<Map<String, Object>> getChildMap(String PID, List<Map<String, Object>> list) {
        List<Map<String, Object>> listChild = new ArrayList<>();
        for (Map<String, Object> listChildMap : list) {
            if (listChildMap.get("pid").toString().equals(PID)) {
                Map<String, Object> dataMap1 = new HashMap<>();
                dataMap1.put("value", listChildMap.get("NODE_ID") == null ? "" : listChildMap.get("NODE_ID").toString());
                dataMap1.put("label", listChildMap.get("TEXT_NAME") == null ? "" : listChildMap.get("TEXT_NAME").toString());
                dataMap1.put("dsc", listChildMap.get("ROLE_DSC") == null ? "" : listChildMap.get("ROLE_DSC").toString());
                List<Map<String, Object>> listChildnew = new ArrayList<>();
                if (listChildMap.get("STATE").equals("closed")) {
                    listChildnew = getChildMap(listChildMap.get("NODE_ID").toString(), list);
                }
                dataMap1.put("children", listChildnew);
                listChild.add(dataMap1);
            }
        }
        return listChild;
    }

    @PostMapping(value = "/grantRoleAppMenuCode")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "移动端权限新增")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result AppPowerAdd(@RequestBody @ApiParam(value = "权限新增") Power power, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            power.setCreateUser(userInfo.getUserId());
            power.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            boolean flag = roleService.appPowerAdd(power);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("授权成功");
            } else {
                result.setCode(-1);
                result.setMsg("授权失败");
            }
            logService.logAdd(power.toString(), "移动端权限新增", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(power.toString(), "移动端权限新增", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取移动端权限数据
     */
    @PostMapping(value = "/getRoleAppMenuCode")
    @ResponseBody
    @ApiOperation(value = "获取移动端权限数据")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getAppPowerData(@RequestBody @ApiParam(value = "权限信息") Power power, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("V_ROLE_ID", power.getRoleId());
            List<Power> list = roleService.getAppPowerData(map);
            result.setCode(0);
            result.setData(list);
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(power.toString(), "获取移动端权限数据", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(power.toString(), "获取移动端权限数据", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

}
